package com.zmn.oms.zmn.facade.impl.entrust;

import com.google.common.collect.Lists;
import com.zmn.brs.common.enums.EventEnum;
import com.zmn.brs.common.enums.RecordFieldEnum;
import com.zmn.brs.starter.annotation.RecordField;
import com.zmn.brs.starter.annotation.StaffOperateRecord;
import com.zmn.common.utils.date.DateUtil;
import com.zmn.oms.common.constant.OrderStatusConsts;
import com.zmn.oms.common.dto.ResultDTO;
import com.zmn.oms.common.exception.OmsBaseException;
import com.zmn.oms.model.dto.entrust.EntrustOrderDetailDTO;
import com.zmn.oms.model.dto.entrust.NewEntrustOrderDTO;
import com.zmn.oms.model.entity.entrust.EntrustOrder;
import com.zmn.oms.model.entity.entrust.EntrustOrderQuery;
import com.zmn.oms.model.entity.log.EntrustOrderSyncLog;
import com.zmn.oms.model.entity.work.OrderWorkLogChange;
import com.zmn.oms.model.vo.work.ZsOrderWorkVO;
import com.zmn.oms.services.interfaces.log.EntrustOrderSyncLogService;
import com.zmn.oms.services.interfaces.order.OrderChangeService;
import com.zmn.oms.zmn.business.interfaces.entrust.EntrustOrderBService;
import com.zmn.oms.zmn.facade.interfaces.entrust.EntrustOrderFacade;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;
import java.util.Optional;

/**
 * 类描述：
 *
 * @author lhl
 * @date 2020/01/14 17:58
 */
@Service("entrustOrderFacade")
@Slf4j
public class EntrustOrderFacadeImpl implements EntrustOrderFacade {

    @Autowired
    private EntrustOrderBService entrustOrderBService;
    @Autowired
    private OrderChangeService orderChangeService;
    @Autowired
    private EntrustOrderSyncLogService entrustOrderSyncLogService;

    /**
     * 录入订单
     * @param newEntrustOrderDTO
     * @return
     * @throws OmsBaseException
     */
    @Override
    public ResultDTO<EntrustOrder> insertOrder(NewEntrustOrderDTO newEntrustOrderDTO) throws OmsBaseException {
        EntrustOrder entrustOrder = entrustOrderBService.prepareInsertOrder(newEntrustOrderDTO);

        ResultDTO<EntrustOrder> resultDTO = entrustOrderBService.doInsertOrder(entrustOrder);

        try {
            // TODO -lhl 触发新单推送（目前可以简单实现，以后放入日志拦截中处理）
            OrderWorkLogChange orderWorkLogChange = new OrderWorkLogChange();
            orderWorkLogChange.setOperatorId(newEntrustOrderDTO.getOperatorId());
            orderWorkLogChange.setOperatorName(newEntrustOrderDTO.getOperator());
            orderWorkLogChange.setOperatorType(newEntrustOrderDTO.getOperatorType());
            orderWorkLogChange.setLogType(OrderStatusConsts.ORDER_STATUS_INPUT);
            orderWorkLogChange.setOrderId(entrustOrder.getEntrustId());
            orderWorkLogChange.setWorkId(entrustOrder.getEntrustId());
            orderWorkLogChange.setChannelId(entrustOrder.getChannelId());
            orderWorkLogChange.setStatus(entrustOrder.getStatus());
            orderWorkLogChange.setOpTime(DateUtil.getNow());
            orderWorkLogChange.setServCategId(entrustOrder.getServCategId());
            orderChangeService.newEntrustOrderSyncToApi(orderWorkLogChange);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }

        return resultDTO;
    }

    @StaffOperateRecord(staffId = "{{#query.operatorId}}",
            event = EventEnum.WORK_ORDER_EXPORT,
            mapping = {
            @RecordField(field = RecordFieldEnum.STAFF_IP, value = "{{#query.operatorIP}}"),
            @RecordField(field = RecordFieldEnum.PLAT, value = "{{#query.platWork}}")
    })
    @Override
    public ResultDTO<List<ZsOrderWorkVO>> listOrders(EntrustOrderQuery query) throws OmsBaseException {
        ResultDTO<List<EntrustOrder>> listResultDTO = entrustOrderBService.listOrders(query);

        if (listResultDTO.isStatusBool() == false) {
            return ResultDTO.fail(listResultDTO.getMessage());
        }

        // 转 vo
        List<ZsOrderWorkVO> voList = Lists.newArrayList();
        List<EntrustOrder> entrustOrderList = listResultDTO.getData();

        for (EntrustOrder entrustOrder : entrustOrderList) {
            voList.add(convertEntrustOrder2Vo(entrustOrder));
        }

        return ResultDTO.success(voList);
    }

    @Override
    public ResultDTO<EntrustOrder> findById(Long entrustId) throws OmsBaseException {
        return entrustOrderBService.findById(entrustId);
    }

    @Override
    public ResultDTO<EntrustOrderDetailDTO> detail(Long entrustId) throws OmsBaseException {
        ResultDTO<EntrustOrder> entrustOrderResult = entrustOrderBService.findById(entrustId);

        if (entrustOrderResult.isStatusBool() == false) {
            return ResultDTO.fail(entrustOrderResult.getMessage());
        }

        EntrustOrderDetailDTO entrustOrderDetailDTO = new EntrustOrderDetailDTO();
        //entrustOrderDetailDTO.setEntrustOrder(entrustOrderResult.getData());
        entrustOrderDetailDTO.setEntrustOrder(convertEntrustOrder2Vo(entrustOrderResult.getData()));

        // 同步日志
        List<EntrustOrderSyncLog> entrustOrderSyncLogs = entrustOrderSyncLogService.listByEntrustOrderId(entrustId);
        entrustOrderDetailDTO.setEntrustOrderSyncLogs(entrustOrderSyncLogs);

        return ResultDTO.success(entrustOrderDetailDTO);
    }

    private ZsOrderWorkVO convertEntrustOrder2Vo(EntrustOrder entrustOrder) {
        ZsOrderWorkVO vo = new ZsOrderWorkVO();
        BeanUtils.copyProperties(entrustOrder, vo);

        vo.setOrderId(entrustOrder.getEntrustId());
        vo.setWorkId(entrustOrder.getEntrustId());
        vo.setReceiveTime(entrustOrder.getCreateTime());
        vo.setDeptName(entrustOrder.getCreaterDeptName());

        vo.setUsername(entrustOrder.getUserName());
        vo.setUserAddress(entrustOrder.getAddress());
        vo.setUserStreet(entrustOrder.getStreet());
        vo.setUserPhone(entrustOrder.getUserPhone());
        vo.setCurrentRemark(entrustOrder.getRemark());

        vo.setStatusName(getEntrustOrderStatusName(entrustOrder.getStatus()));
        vo.setMasterName(Optional.ofNullable(entrustOrder.getMasterName()).orElse(""));
        vo.setMasterPhone(Optional.ofNullable(entrustOrder.getMasterPhone()).orElse(""));

        vo.setProductInfo(String.format("%s*%d", entrustOrder.getProductName(), entrustOrder.getProductNumber()));
        vo.setTypeName("新单");
        vo.setChannelName(Optional.ofNullable(entrustOrder.getChannelFromName()).orElse(""));
        vo.setTotalAmount(entrustOrder.getTotalAmount());

        return vo;
    }

    private String getEntrustOrderStatusName(int status) {
        switch (status) {
            case OrderStatusConsts.ORDER_STATUS_INPUT:
                return "已录入";
            case OrderStatusConsts.ORDER_STATUS_CONFIRM:
                return "已确认";
            case OrderStatusConsts.ORDER_STATUS_DISTRIBUTE:
                return "已派单";
            case OrderStatusConsts.ORDER_STATUS_TAKE:
                return "已领单";
            case OrderStatusConsts.ORDER_STATUS_VISIT:
                return "已上门";
            case OrderStatusConsts.ORDER_STATUS_COMPLETE:
                return "已完成";
            case OrderStatusConsts.ORDER_STATUS_CANCEL:
                return "已取消";
            default:
                return "未知";
        }
    }
}
